﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace Worktool.CODE_Chris.Forms.Update
{
    public delegate void BytesDownloadedEventHandler(ByteArgs e);

    public class ByteArgs : EventArgs
    {
        private int _downloaded;
        private int _total;

        public int downloaded
        {
            get
            {
                return _downloaded;
            }
            set
            {
                _downloaded = value;
            }
        }

        public int total
        {
            get
            {
                return _total;
            }
            set
            {
                _total = value;
            }
        }

    }

    class WebData
    {
        public static event BytesDownloadedEventHandler bytesDownloaded;

        public static bool downloadInfoFromWeb(string URL, string file, string targetFolder)
        {
            try
            {

                byte[] downloadedData;


                downloadedData = new byte[0];

                //open a data stream from the supplied URL
                WebRequest webReq = WebRequest.Create(URL);
                webReq.Method = WebRequestMethods.Ftp.ListDirectory;
                WebResponse webResponse = webReq.GetResponse();
                Stream dataStream = webResponse.GetResponseStream();

                StreamReader streamReader = new StreamReader(webResponse.GetResponseStream());

                //Dateien in Liste schreiben
                List<string> fileNames = new List<string>();
                string line = streamReader.ReadLine();
                while (!string.IsNullOrEmpty(line))
                {
                    if (line.Contains(".zip")) fileNames.Add(line);
                    line = streamReader.ReadLine();
                }

                String version = SearchForUpdates.versionNr;
                String newVersion = "";
                String newDate = "";
                String newFileName = "";

                //Liste sortieren
                List<string> orderedFileNames = fileNames.OrderBy(x => x.ToString()).ToList();

                //Nächste Version ermitteln
                foreach (string item in orderedFileNames)
                {
                    if (Convert.ToInt64(item.Replace(".zip", "").Split('_')[1].Replace(".", "")) > Convert.ToInt64(version.Replace(".", "")))
                    {
                        newVersion = item.Replace(".zip", "").Split('_')[1];
                        newDate = item.Replace(".zip", "").Split('_')[0].Substring(0, 2) + "/" + item.Replace(".zip", "").Split('_')[0].Substring(2, 2) + "/" + item.Replace(".zip", "").Split('_')[0].Substring(4, 4);
                        newFileName = item;
                        break;
                    }
                }

                //Daten für die Textdatei festlegen
                String header = "";
                String data = "";
                if (newVersion != "" && newDate != "" && newFileName != "")
                {
                    header = "app|version|release date|url|file";
                    data = "Worktool|" + newVersion + "|" + newDate + "|" + URL + "|" + newFileName;
                }
                else
                {
                    newVersion = "1.0.0000.00000";
                    newDate = "01/01/1900";
                    newFileName = "Keine_Datei_Vorhanden";
                    header = "app|version|release date|url|file";
                    data = "Worktool|" + newVersion + "|" + newDate + "|" + URL + "|" + newFileName;
                }


                //Datei in Update-Folder schreiben
                if (File.Exists(targetFolder + "UM.txt")) File.Delete(targetFolder + "UM.txt");

                using (FileStream fs = new FileStream(targetFolder + "UM.txt", FileMode.Append, FileAccess.Write))
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.WriteLine(header);
                    sw.WriteLine(data);
                }

                return true;

            }

            catch (Exception e)
            {
                //We may not be connected to the internet
                //Or the URL may be incorrect
                return false;
            }

        }
    }
}
